﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitcoinLibrary
{
    public class AddressMessage : Message
    {
        private const long serialVersionUID = 8058283864924679460L;
        private const long MAX_ADDRESSES = 1024;
        List<PeerAddress> addresses;

        public AddressMessage(NetworkParameters param, byte[] payload, int offset)
            : base(param, payload, offset)
        {
        }

        public AddressMessage(NetworkParameters param, byte[] payload)
            : base(param, payload, 0)
        {
        }

        public override void parse()
        {
            long numAddresses = readVarInt();
            // Guard against ultra large messages that will crash us.
            if (numAddresses > MAX_ADDRESSES)
                throw new Exception("Address message too large.");  // TODO: add ProtocolException!
            addresses = new List<PeerAddress>((int)numAddresses);
            for (int i = 0; i < numAddresses; i++)
            {
                PeerAddress addr = new PeerAddress(param, bytes, cursor, protocolVersion);
                addresses.Add(addr);
                cursor += addr.getMessageSize();
            }
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("addr: ");
            foreach (PeerAddress a in addresses)
            {
                builder.Append(a.ToString());
                builder.Append(" ");
            }
            return builder.ToString();
        }
    }
}
